package com.mt.demo.socket;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.mt.demo.manager.MeetingRoomManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class WebRTCSignalingHandler {

    @Autowired
    private MeetingRoomManager meetingRoomManager;

    // WebRTC SDP Offer 处理
    @OnEvent("webrtc-offer")
    public void onWebRTCOffer(SocketIOClient client, Map<String, Object> data, AckRequest ackRequest) {
        String roomId = client.getHandshakeData().getSingleUrlParam("roomId");
        String fromUserId = client.getHandshakeData().getSingleUrlParam("userId");
        String toUserId = (String) data.get("toUserId");

        // 构建转发数据
        data.put("fromUserId", fromUserId);

        // 如果指定了目标用户，只发送给该用户
        if (toUserId != null && !toUserId.isEmpty()) {
            meetingRoomManager.getRoomClients(roomId).forEach(roomClient -> {
                String clientUserId = roomClient.getHandshakeData().getSingleUrlParam("userId");
                if (toUserId.equals(clientUserId)) {
                    roomClient.sendEvent("webrtc-offer", data);
                }
            });
        } else {
            // 否则广播给房间内所有其他用户
            meetingRoomManager.getRoomClients(roomId).forEach(roomClient -> {
                if (!roomClient.getSessionId().equals(client.getSessionId())) {
                    roomClient.sendEvent("webrtc-offer", data);
                }
            });
        }
    }

    // WebRTC SDP Answer 处理
    @OnEvent("webrtc-answer")
    public void onWebRTCAnswer(SocketIOClient client, Map<String, Object> data, AckRequest ackRequest) {
        String roomId = client.getHandshakeData().getSingleUrlParam("roomId");
        String fromUserId = client.getHandshakeData().getSingleUrlParam("userId");
        String toUserId = (String) data.get("toUserId");

        // 构建转发数据
        data.put("fromUserId", fromUserId);

        // 发送给指定用户
        if (toUserId != null && !toUserId.isEmpty()) {
            meetingRoomManager.getRoomClients(roomId).forEach(roomClient -> {
                String clientUserId = roomClient.getHandshakeData().getSingleUrlParam("userId");
                if (toUserId.equals(clientUserId)) {
                    roomClient.sendEvent("webrtc-answer", data);
                }
            });
        }
    }

    // WebRTC ICE Candidate 处理
    @OnEvent("webrtc-ice-candidate")
    public void onWebRTCIceCandidate(SocketIOClient client, Map<String, Object> data, AckRequest ackRequest) {
        String roomId = client.getHandshakeData().getSingleUrlParam("roomId");
        String fromUserId = client.getHandshakeData().getSingleUrlParam("userId");
        String toUserId = (String) data.get("toUserId");

        // 构建转发数据
        data.put("fromUserId", fromUserId);

        // 如果指定了目标用户，只发送给该用户
        if (toUserId != null && !toUserId.isEmpty()) {
            meetingRoomManager.getRoomClients(roomId).forEach(roomClient -> {
                String clientUserId = roomClient.getHandshakeData().getSingleUrlParam("userId");
                if (toUserId.equals(clientUserId)) {
                    roomClient.sendEvent("webrtc-ice-candidate", data);
                }
            });
        } else {
            // 否则广播给房间内所有其他用户
            meetingRoomManager.getRoomClients(roomId).forEach(roomClient -> {
                if (!roomClient.getSessionId().equals(client.getSessionId())) {
                    roomClient.sendEvent("webrtc-ice-candidate", data);
                }
            });
        }
    }

    // 用户准备好接收媒体流
    @OnEvent("ready-to-receive")
    public void onReadyToReceive(SocketIOClient client, Map<String, Object> data, AckRequest ackRequest) {
        String roomId = client.getHandshakeData().getSingleUrlParam("roomId");
        String userId = client.getHandshakeData().getSingleUrlParam("userId");

        data.put("userId", userId);

        // 通知房间内其他用户
        meetingRoomManager.getRoomClients(roomId).forEach(roomClient -> {
            if (!roomClient.getSessionId().equals(client.getSessionId())) {
                roomClient.sendEvent("user-ready-to-receive", data);
            }
        });
    }

    // 用户开始发送媒体流
    @OnEvent("media-stream-start")
    public void onMediaStreamStart(SocketIOClient client, Map<String, Object> data, AckRequest ackRequest) {
        String roomId = client.getHandshakeData().getSingleUrlParam("roomId");
        String userId = client.getHandshakeData().getSingleUrlParam("userId");

        data.put("userId", userId);

        // 通知房间内其他用户
        meetingRoomManager.getRoomClients(roomId).forEach(roomClient -> {
            if (!roomClient.getSessionId().equals(client.getSessionId())) {
                roomClient.sendEvent("media-stream-started", data);
            }
        });
    }

    // 用户停止发送媒体流
    @OnEvent("media-stream-stop")
    public void onMediaStreamStop(SocketIOClient client, Map<String, Object> data, AckRequest ackRequest) {
        String roomId = client.getHandshakeData().getSingleUrlParam("roomId");
        String userId = client.getHandshakeData().getSingleUrlParam("userId");

        data.put("userId", userId);

        // 通知房间内其他用户
        meetingRoomManager.getRoomClients(roomId).forEach(roomClient -> {
            if (!roomClient.getSessionId().equals(client.getSessionId())) {
                roomClient.sendEvent("media-stream-stopped", data);
            }
        });
    }
}
